<?php declare(strict_types=1);

namespace App\Api\V2\Controller\Device;


use App\Api\Controllers\BaseController;
use App\Models\Device;
use App\Models\MerchantStore;
use App\Traits\ResponseTrait;
use App\Util\ExeclUtil;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class DeviceController extends BaseController
{

    use ResponseTrait;

    public function type()
    {
        $types = Device::query()->select(["device_name", "device_type"])->groupBy(["device_name", "device_type"])->get()->toArray();
        return $this->successResponse("ok", ["data" => $types]);
    }

    public function listsDevice(Request $request)
    {
        $page = [
            "page" => (int)$request->input("page", 1),
            "pagesize" => (int)$request->input("pagesize", 15),
        ];
//        $user=$this->parseToken();
        $where = [
            "device_type" => $request->input("device_type", ""),
            "store_id" => $request->input("store_id", ""),
            "merchant_id" => $request->input("merchant_id", ""),
            "device_no"=>$request->input("device_no","")
        ];
        $query = Device::query()->where(function ($query) use ($where) {
            if (!empty($where["merchant_id"])) {
                $query->where("merchant_id", $where["merchant_id"]);
            }
            if (!empty($where["store_id"])) {
                $query->where("store_id", $where["store_id"]);
            }
            if (!empty($where["device_type"])) {
                $query->where("device_type", $where["device_type"]);
            }
            if (!empty($where["device_no"])) {
                $query->where("device_no", "like","%".$where["device_no"]."%");
            }
        });
        $total = (clone $query)->count();
        $list = (clone $query)->limit($page["pagesize"])->offset(($page["page"] - 1) * $page["pagesize"])
            ->orderBy("id","desc")->get()->toArray();
        return $this->successResponse("ok", [
            "total" => $total,
            "list" => $list
        ]);
    }


    public function listsDeviceExport(Request $request)
    {
//        $user=$this->parseToken();
        $where = [
            "device_type" => $request->input("device_type", ""),
            "store_id" => $request->input("store_id", ""),
            "merchant_id" => $request->input("merchant_id", ""),
            "device_no"=>$request->input("device_no","")
        ];
        $query = Device::query()->where(function ($query) use ($where) {
            if (!empty($where["merchant_id"])) {
                $query->where("merchant_id", $where["merchant_id"]);
            }
            if (!empty($where["store_id"])) {
                $query->where("store_id", $where["store_id"]);
            }
            if (!empty($where["device_type"])) {
                $query->where("device_type", $where["device_type"]);
            }
            if (!empty($where["device_no"])) {
                $query->where("device_no", "like","%".$where["device_no"]."%");
            }
        });
        $list = (clone $query)->get()->toArray();
        //加代理商名称
        $stores = DB::table('stores')->pluck('user_id', 'store_id')->all();
        $users = DB::table('users')->pluck('name', 'id')->all();
        foreach ($list as &$item) {
            $storeId = $item["store_id"];
            if (isset($stores[$storeId])) {
                $userId = $stores[$storeId];
                $item["user_id"] = $userId;
                $item["username"] = $users[$userId] ?? '';
            } else {
                $item["user_id"] = null;
                $item["username"] = '';
            }
        }
        unset($item);
        //处理导出
        //在这里导出
        $title = [
            "设备号", "店铺ID", "店铺名称", "设备类型", "设备类型名称", "收银员", "设备key", "绑定时间", "代理商名称"
        ];
        $value = [];
        //写入execl
        foreach ($list as $v) {
            $value[] = [
                $v["device_no"],
                $v["store_id"],
                $v["store_name"],
                $v["device_type"],
                $v["device_name"],
                $v["merchant_name"],
                $v["device_key"],
                $v["created_at"],
                $v["username"],
            ];
        }
        //写入excel
        $util = new ExeclUtil();
        $fileName = "设备导出列表_" . uniqid((string)time()) . ".csv";
        $filePath = public_path("/uploads/csv/" . date("Y/md", time()) . "/");
        if (!is_dir($filePath)) {
            mkdir($filePath, 0777, true);
        }
        $util->exportToExcel($filePath . $fileName, [], $title, $value);
        $url = $util->uploadOss($filePath . $fileName, $fileName);
        //删除文件
        if (file_exists($filePath . $fileName)) {
            unlink($filePath . $fileName);
        }
        //删除fileName
        return $this->successResponse("ok", ["url" => $url]);
    }


}
